/**
 * 实例诊断工具
 * 用于在运行时检测多实例问题
 */

export interface DiagnosticResult {
  windowId: string
  timestamp: number
  websocket: {
    hasInstance: boolean
    instanceId: string | null
    processId: string | null
    isConnected: boolean
    currentUrl: string | null
    messageHandlerCount: number
    instanceCount: number
    allInstances: string[]
  }
  store: {
    hasPinia: boolean
    serverPorts: any
    storeInstanceId: string | null
  }
  component: {
    currentRoute: string
    lifecycleState: string
    isKeepAlive: boolean
  }
  electron: {
    processId: number | null
    availablePorts: any
    apiMethods: string[]
  }
}

export class InstanceDiagnostic {
  private static instance: InstanceDiagnostic
  private windowId: string
  private diagnosticResults: DiagnosticResult[] = []

  constructor() {
    this.windowId = this.generateWindowId()
    console.log(`🔍 实例诊断工具初始化 - 窗口ID: ${this.windowId}`)
  }

  static getInstance(): InstanceDiagnostic {
    if (!this.instance) {
      this.instance = new InstanceDiagnostic()
    }
    return this.instance
  }

  private generateWindowId(): string {
    return `window_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  }

  /**
   * 执行完整诊断
   */
  async runFullDiagnostic(): Promise<DiagnosticResult> {
    console.log('🚀 开始实例诊断...')
    
    const result: DiagnosticResult = {
      windowId: this.windowId,
      timestamp: Date.now(),
      websocket: await this.diagnoseWebSocket(),
      store: await this.diagnoseStore(),
      component: await this.diagnoseComponent(),
      electron: await this.diagnoseElectron()
    }

    this.diagnosticResults.push(result)
    this.logDiagnosticResult(result)
    
    return result
  }

  /**
   * 诊断WebSocket状态
   */
  private async diagnoseWebSocket(): Promise<DiagnosticResult['websocket']> {
    try {
      // 动态导入WebSocket类
      const { WebsocketIo } = await import('./websocket')
      
      // 获取当前进程的实例
      const wsInstance = WebsocketIo.getInstance()
      
      // 获取所有实例信息
      const allInstances = WebsocketIo.getAllInstances()
      const instanceCount = WebsocketIo.getInstanceCount()
      const allInstanceIds = Array.from(allInstances.keys())
      
      // 获取当前实例状态
      const instanceStatus = wsInstance ? wsInstance.getInstanceStatus() : null
      
      return {
        hasInstance: !!wsInstance,
        instanceId: instanceStatus ? instanceStatus.processId : null,
        processId: instanceStatus ? instanceStatus.processId : null,
        isConnected: instanceStatus ? instanceStatus.isConnected : false,
        currentUrl: instanceStatus ? instanceStatus.connectionUrl : null,
        messageHandlerCount: instanceStatus ? instanceStatus.messageHandlerCount : 0,
        instanceCount: instanceCount,
        allInstances: allInstanceIds
      }
    } catch (error) {
      console.error('WebSocket诊断失败:', error)
      return {
        hasInstance: false,
        instanceId: null,
        processId: null,
        isConnected: false,
        currentUrl: null,
        messageHandlerCount: 0,
        instanceCount: 0,
        allInstances: []
      }
    }
  }

  /**
   * 诊断Store状态
   */
  private async diagnoseStore(): Promise<DiagnosticResult['store']> {
    try {
      // 动态导入store
      const { useServerStore } = await import('../store/server')
      const serverStore = useServerStore()
      
      return {
        hasPinia: !!(window as any).pinia,
        serverPorts: serverStore.ports,
        storeInstanceId: `${serverStore.$id}_${Date.now()}`
      }
    } catch (error) {
      console.error('Store诊断失败:', error)
      return {
        hasPinia: false,
        serverPorts: null,
        storeInstanceId: null
      }
    }
  }

  /**
   * 诊断组件状态
   */
  private async diagnoseComponent(): Promise<DiagnosticResult['component']> {
    try {
      return {
        currentRoute: window.location.hash,
        lifecycleState: this.detectLifecycleState(),
        isKeepAlive: this.detectKeepAlive()
      }
    } catch (error) {
      console.error('组件诊断失败:', error)
      return {
        currentRoute: 'unknown',
        lifecycleState: 'unknown',
        isKeepAlive: false
      }
    }
  }

  /**
   * 诊断Electron API状态
   */
  private async diagnoseElectron(): Promise<DiagnosticResult['electron']> {
    try {
      const electronAPI = (window as any).electronAPI
      
      return {
        processId: electronAPI?.getProcessId ? electronAPI.getProcessId() : null,
        availablePorts: electronAPI?.getServerPorts ? electronAPI.getServerPorts() : null,
        apiMethods: electronAPI ? Object.keys(electronAPI) : []
      }
    } catch (error) {
      console.error('Electron诊断失败:', error)
      return {
        processId: null,
        availablePorts: null,
        apiMethods: []
      }
    }
  }

  /**
   * 检测生命周期状态
   */
  private detectLifecycleState(): string {
    // 检查是否在Vue组件中
    const app = document.querySelector('#app')
    if (app) {
      // 检查Vue实例
      const vueInstance = (app as any).__vue__ || (app as any)._vnode
      if (vueInstance) {
        return 'vue_mounted'
      }
    }
    return 'unknown'
  }

  /**
   * 检测keep-alive状态
   */
  private detectKeepAlive(): boolean {
    try {
      // 检查路由配置中的keep-alive设置
      const router = (window as any).$router
      if (router && router.currentRoute) {
        return router.currentRoute.meta?.keepAlive === true
      }
      return false
    } catch {
      return false
    }
  }

  /**
   * 输出诊断结果
   */
  private logDiagnosticResult(result: DiagnosticResult): void {
    console.group(`🔍 实例诊断结果 - ${result.windowId}`)
    
    console.group('📡 WebSocket状态')
    console.log('实例存在:', result.websocket.hasInstance ? '✅' : '❌')
    console.log('进程ID:', result.websocket.processId)
    console.log('实例ID:', result.websocket.instanceId)
    console.log('连接状态:', result.websocket.isConnected ? '✅ 已连接' : '❌ 未连接')
    console.log('当前URL:', result.websocket.currentUrl)
    console.log('消息处理器数量:', result.websocket.messageHandlerCount)
    console.log('总实例数量:', result.websocket.instanceCount)
    console.log('所有实例:', result.websocket.allInstances)
    console.groupEnd()
    
    console.group('🗄️ Store状态')
    console.log('Pinia存在:', result.store.hasPinia ? '✅' : '❌')
    console.log('Store实例ID:', result.store.storeInstanceId)
    console.log('服务器端口:', result.store.serverPorts)
    console.groupEnd()
    
    console.group('🧩 组件状态')
    console.log('当前路由:', result.component.currentRoute)
    console.log('生命周期状态:', result.component.lifecycleState)
    console.log('Keep-Alive:', result.component.isKeepAlive ? '✅ 启用' : '❌ 禁用')
    console.groupEnd()
    
    console.group('⚡ Electron状态')
    console.log('进程ID:', result.electron.processId)
    console.log('可用端口:', result.electron.availablePorts)
    console.log('API方法:', result.electron.apiMethods)
    console.groupEnd()
    
    console.groupEnd()
  }

  /**
   * 比较多个实例的诊断结果
   */
  static compareResults(results: DiagnosticResult[]): void {
    if (results.length < 2) {
      console.warn('需要至少2个诊断结果才能进行比较')
      return
    }

    console.group('🔄 多实例比较分析')
    
    // WebSocket比较
    const wsProcessIds = results.map(r => r.websocket.processId)
    const wsInstanceIds = results.map(r => r.websocket.instanceId)
    const wsUrls = results.map(r => r.websocket.currentUrl)
    const wsInstanceCounts = results.map(r => r.websocket.instanceCount)
    const wsAllInstances = results.map(r => r.websocket.allInstances)
    
    const hasSameWsProcessId = new Set(wsProcessIds).size === 1
    const hasSameWsInstance = new Set(wsInstanceIds).size === 1
    const hasSameWsUrl = new Set(wsUrls).size === 1
    const maxInstanceCount = Math.max(...wsInstanceCounts)
    
    console.group('📡 WebSocket比较')
    console.log('进程ID相同:', hasSameWsProcessId ? '❌ 问题 - 应该不同' : '✅ 正常')
    console.log('实例ID相同:', hasSameWsInstance ? '❌ 问题 - 应该不同' : '✅ 正常')
    console.log('连接URL基础相同:', hasSameWsUrl ? '⚠️ 预期行为' : '✅ 正常')
    console.log('最大实例数量:', maxInstanceCount)
    console.log('进程ID列表:', wsProcessIds)
    console.log('实例ID列表:', wsInstanceIds)
    console.log('所有实例详情:', wsAllInstances)
    console.groupEnd()
    
    // Store比较
    const storePorts = results.map(r => JSON.stringify(r.store.serverPorts))
    const storeInstanceIds = results.map(r => r.store.storeInstanceId)
    const hasSameStorePorts = new Set(storePorts).size === 1
    const hasSameStoreInstance = new Set(storeInstanceIds).size === 1
    
    console.group('🗄️ Store比较')
    console.log('端口配置相同:', hasSameStorePorts ? '❌ 问题' : '✅ 正常')
    console.log('Store实例相同:', hasSameStoreInstance ? '❌ 问题' : '✅ 正常')
    console.groupEnd()
    
    // Electron比较
    const processIds = results.map(r => r.electron.processId)
    const hasSameProcessId = new Set(processIds).size === 1
    
    console.group('⚡ Electron比较')
    console.log('进程ID相同:', hasSameProcessId ? '❌ 问题' : '✅ 正常')
    console.log('进程ID列表:', processIds)
    console.groupEnd()
    
    console.groupEnd()
  }

  /**
   * 获取所有诊断结果
   */
  getAllResults(): DiagnosticResult[] {
    return [...this.diagnosticResults]
  }

  /**
   * 清除诊断结果
   */
  clearResults(): void {
    this.diagnosticResults = []
  }

  /**
   * 导出诊断结果为JSON
   */
  exportResults(): string {
    return JSON.stringify({
      diagnosticTime: new Date().toISOString(),
      windowId: this.windowId,
      results: this.diagnosticResults
    }, null, 2)
  }
}

// 全局暴露诊断工具
if (typeof window !== 'undefined') {
  (window as any).instanceDiagnostic = InstanceDiagnostic.getInstance()
}

export default InstanceDiagnostic